<template>
  <div>
    <app-head title="绑定手机"></app-head>

    <div class="bind">
      <div class="h5form">
        <div class="h5form-item">
          <input class="h5form-input" v-model="mobile" placeholder="请输入正确的手机号" type="text" />
        </div>

        <div class="h5form-item">
          <input class="h5form-input" v-model="code" placeholder="请输入动态验证码" type="text" />
          <button
            class="h5form-getcode"
            :disabled="codeText !== '获取验证码'"
            @click="handleCode"
          >{{codeText}}</button>
        </div>

        <div class="h5form-item" v-if="isWechat">
          <input class="h5form-input" v-model="password" placeholder="请输入登录密码" type="text" />
        </div>

        <div class="h5form-submit">
          <button @click="handleBind">完成绑定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import api from "@/api";
export default {
  name: "bind",
  components: {},
  data() {
    return {
      mobile: "",
      code: "",
      codeText: "获取验证码",
      isWechat: false,
      password: ""
    };
  },
  computed: {},
  methods: {
    handleBind() {
      if (!/^1[0-9]{10}/.test(this.mobile)) {
        this.$tips("手机号格式有误！");
        return false;
      }
      if (!this.code) {
        this.$tips("请输入动态验证码！");
        return false;
      }
      if (this.isWechat && !this.password) {
        this.$tips("请输入登录密码！");
        return false;
      }
      let data = {
        "sms-type": 6,
        "sms-mobile": this.mobile,
        "sms-code": this.code
      };
      if (this.password) {
        data.password = this.password;
      }
      api.bindMobile(
        data,
        res => {
          if (this.$route.query.from === "game") {
            this.$tips("手机绑定成功，即将返回游戏");
            window.setTimeout(() => {
              this.$router.go(-1);
            }, 500);
          } else {
            this.$tips(res);
            this.$router.push("/user");
          }
        },
        msg => {
          this.$tips(msg);
        }
      );
    },
    handleCode() {
      if (!/^1[0-9]{10}/.test(this.mobile)) {
        this.$tips("手机号格式有误！");
      }
      api.smsSend(
        {
          "sms-type": 6,
          "sms-mobile": this.mobile
        },
        res => {
          this.$tips(res);
          this.codeText = 120;
          let timer = setInterval(() => {
            this.codeText--;
            if (this.codeText < 0) {
              clearInterval(timer);
              this.codeText = "获取验证码";
            }
          }, 1000);
        },
        msg => {
          this.$tips(msg);
        }
      );
    }
  },
  created() {}
};
</script>

<style scoped="scoped" lang="scss">
.bind {
  padding-top: 0.3rem;
}
</style>
